<template>
	<view class="page__content">
		<u-navbar :title="TitleName" @leftClick="leftClick" leftIconColor="#fff" rightIconColor="#fff" :autoBack="true"
			:fixed="false">
		</u-navbar>

		<!-- 设备列表 -->
		<view class="page__content__main">
			<view class="x-f" style="padding: 15px 30px;margin-top: 15px;background-color: #fff;border-radius: 20px;"
				v-for="(item,index) in DeviceInfoList" :key="index" @click="ChoiceDevice(item)">
				<u--image :showLoading="true" :src="judgeImg(item.FilePath)" mode="widthFix" width="35px"
					height="35px"></u--image>

				<view style="margin-left: 15px;flex: 1;">
					<view class="x-f" style="font-size: 14px;font-weight: 600;">
						<text>{{item.MeasureName}}</text>
						<text>_</text>
						<text>{{item.MeasureSpec}}</text>
					</view>

					<view style="margin-top: 8px;">
						<u-tag style="width: fit-content;" size="mini" :text="item.Communication"></u-tag>
					</view>
				</view>

				<u-icon v-if="item.MeasureID == selectedDevice.MeasureID" name="checkbox-mark" color="#32c238"
					size="20"></u-icon>
			</view>
		</view>


		<!-- 品牌筛选 -->
		<!-- <u-popup :show="ShowBrandFiltering" round :safeAreaInsetTop="true" mode="left" @close="close" @open="open">
			<view style="padding: 10px 15px;display: flex;flex-direction: column;" :style="`width: ${PopupWidth}px`">

				<view class="page">
					<view class="wraper">
						<view class="header" style="display: flex;justify-content: space-between;align-items: center;">
							<text style="font-size: 20px;font-weight: 600;">品牌筛选</text>

							<u-icon name="close" color="#999" size="18" @click="close"
								style="display: block;width: 50rpx;height: 50px;"></u-icon>

						</view>

						<view id="MainBox" class="main" :style="{height: Height.Main - 50 + 'px'}">
							<scroll-view class="main-scroll" scroll-y style="height: 100%">
								<view class="main-list">

									<view style="text-align: right;">
										<text style="color: #999;margin-left:6px;font-size: 14px;"
											@click="CheckAll">全选</text>

										<text style="color: #999;margin-left:6px;font-size: 14px;">|</text>

										<text style="color: #999;margin-left:6px;font-size: 14px;"
											@click="ResetBtn">重置</text>
									</view>

									<view class="GridList">
										<view class="GridCardBox" v-for="(item,index) in GridBrandList" :key="index"
											@click="CheckedCard(item,index)">
											<view style="margin-top: 40rpx;">
												<u--image :showLoading="true" :src="judgeImg(item.FilePath)"
													mode="widthFix" width="100%" height="60px"></u--image>
											</view>
											<view class="textBox">
												<text>{{item.Brand}}</text>
											</view>


											<u-icon v-if="item.Checked"
												style="position: absolute;top:3px;right:3px;display: block;padding:3px;background: #1aafff;border-radius:50px;"
												name="checkbox-mark" color="#fff" size="12px"></u-icon>
										</view>
									</view>

								</view>
							</scroll-view>
						</view>

						<view class='footer'>
							<view>
								<u-button type="primary" text="筛选" @click="SiftSubBtn"></u-button>
							</view>
						</view>
					</view>
				</view>


			</view>
		</u-popup> -->

	</view>
</template>

<script>
	// import TheSonAgreement from '@/static/js/Agreement/5101_Sanhe_YBKC.js'
	export default {
		data() {
			return {
				TitleName: '',
				ClassifyID: '',
				DeviceInfoList: [], // 设备列表
				selectedDevice: {},
				ShowBrandFiltering: false, // 品牌筛选弹窗
				GridBrandList: [], // 品牌筛选列表
				Height: {
					Top: 0,
					Main: 0,
					footer: 0
				},
				ColSpan: 12,
			}
		},
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			var that = this;
			that.TitleName = option.Name;
			that.ClassifyID = option.ClassifyID

			// 获取设备列表数据
			that.GetDeviceInfoArr(option.ClassifyID, '');

			// 获取品牌数据
			that.GetBrandList()

			// uni.$on("sendDeviceType", function(data) {
			// 	that.TitleName = data.DeviceBluetoothTypeName;
			// 	that.GetDeviceInfoArr(data.DeviceBluetoothTypeID);
			// })

		},
		created() {
			// 同步获取系统信息
			let systemInfo = uni.getSystemInfoSync()
			// px转rpx
			// let pxToRpxScale = 750 / systemInfo.windowWidth;
			// 可视窗口宽度
			let ktxWindowWidth = systemInfo.windowWidth
			// console.log(ktxWindowWidth)

			if (ktxWindowWidth <= 500) { // 一行两个
				this.ColSpan = 12
			} else if (ktxWindowWidth > 500 && ktxWindowWidth < 1000) { // 一行三个
				this.ColSpan = 8
			}
		},
		computed: {
			PopupWidth() { // 品牌筛选弹窗 屏幕宽度
				return uni.getSystemInfoSync().screenWidth * (0.8)
			}
		},
		methods: {
			setSwiperHeight(data, Cla) {
				var that = this
				let query = uni.createSelectorQuery().in(this);

				query.select(data).boundingClientRect(); //我找的idimgBox 你的替换就行
				query.exec(res => {
					that.Height[Cla] = res[0].height
				});

			},
			open() { // 品牌筛选弹层打开触发
				var that = this
				// console.log('open');
				that.ShowBrandFiltering = true

				that.$nextTick(() => {
					that.setSwiperHeight('.header', 'Top')
					that.setSwiperHeight('.header', 'footer')

					// console.log(that.Height.Top)
					// console.log(that.Height.footer)

					that.Height.Main = uni.getSystemInfoSync().screenHeight - that.Height.Top - that.Height.footer
					// console.log(uni.getSystemInfoSync().screenHeight)
					// console.log(uni.getSystemInfoSync().screenHeight - that.Height.Top - that.Height.footer)

				});
			},
			CheckedCard(data, index) { // 点击品牌card
				var that = this
				data.Checked = !data.Checked
			},
			CheckAll() { // 全选
				var that = this

				that.GridBrandList.map(item => {
					item.Checked = true
				})
			},
			ResetBtn() { // 重置品牌筛选，将选项还原
				var that = this
				that.GridBrandList.map(item => {
					item.Checked = false
				})
			},
			close() { // 品牌筛选弹层关闭触发
				this.ShowBrandFiltering = false
				// 关闭后重置品牌选项
				this.ResetBtn()
			},
			SiftSubBtn() { // 确认筛选按钮
				var that = this
				// console.log(that.GridBrandList)

				let ChoiceArr = that.GridBrandList.filter(item => {
					return item.Checked
				})

				// 如果筛选弹窗中，选中项数量 == 品牌总数 || == 0，则显示全部； 反之筛选对应数据
				/* 
				 * DeviceInfoList   	显示的列表数据
				 */

				let Ids = ''
				if (ChoiceArr.length == 0 || ChoiceArr.length == that.GridBrandList.length) {
					// 全部，设为空 

				} else {
					let IDs = []
					// 多选，以逗号隔开
					console.log('筛选')
					ChoiceArr.forEach(item => {
						IDs.push(item.EquipmentBrandID)
					})
					Ids = IDs.join(',')
				}

				that.GetDeviceInfoArr(that.ClassifyID, Ids)

				that.close()
			},
			judgeImg(data) {
				var that = this
				if (data == null) {
					return ''
				} else if (!/^http[s]?:\/\/.*/.test(data)) {
					return 'http://' + that.Request.serverIP() + data
					// return 'http://' + '39.105.222.87:20000' + data
				} else {
					return data
				}
			},
			GetBrandList() { // 获取品牌数据
				var that = this;
				try {
					that.Request.request('selectPPList', {}, function(res) {
						console.log(res)
						if (res.status == 200) {

							let list = JSON.parse(JSON.stringify(res.data.ds))

							list.forEach(item => {
								item.Checked = false
							})
							that.GridBrandList = list
						}

					})

				} catch (error) {
					//TODO handle the exception
				}
			},
			GetDeviceInfoArr(ID, Ids) { // 获取设备列表
				var that = this

				let obj = {}

				if (Ids) {
					obj = {
						UpID: ID,
						EquipmentBrandID: Ids
					}
				} else {
					obj = {
						UpID: ID,
					}
				}

				that.Request.request('APP_JLSBLIST', obj, function(res) {
					if (res.status == 200) {
						console.log(res);

						that.DeviceInfoList = res.data.ds
					}

				})
			},
			ChoiceDevice(data) { // 选中设备
				console.log(data);
				// this.selectedDevice = data;

				// 记录选中数据到临时信息中，连接页面退出后会清除
				this.$store.commit("QmsModule/ChangeAndSetStateData", {
					Name1: 'DeviceLinkConfig.tempData_device.deviceInfo',
					data: this.$utils.deepClone(data)
				});

				// 这里直接做跳转连接动作
				uni.navigateTo({
					url: "/st_qms/index/deviceToLink"
				});

			},
			leftClick() { // 返回上一页
				// uni.navigateBack()
			},
			rightClick() { // 点击确认
				var that = this;
				// console.log(that.selectedDevice.BluetoothProtocol)

				if (that.selectedDevice.BluetoothProtocol) {

					// 获取历史存储的设备数据
					const historyDevices = that.$store.getters['QmsModule/DeviceHistory'];
					const currentDevice = that.selectedDevice;

					// 准备新数据
					const prepareDevice = (device, index) => {
						console.log(device);
						device.text = device.MeasureName + device.MeasureSpec;
						device.value = index;
						if (device.FilePath) {
							device.FilePath = that.Request.IPAgreement() + that.Request.serverIP() + device.FilePath;
						}
						return device;
					};

					// 更新存储
					const updateStore = (devices, index = 0) => {
						that.$store.commit('QmsModule/ChangeAndSetStateData', {
							Name1: 'DeviceLinkConfig.DeviceHistory',
							data: devices,
							StorageName: 'Agreement_History_DevicesList',
							StorageData: JSON.stringify(devices)
						});

						that.$store.commit('QmsModule/ChangeAndSetStateData', {
							Name1: 'DeviceLinkConfig.CheckHisValue',
							data: index,
							StorageName: 'CheckHisValue',
							StorageData: JSON.stringify(index)
						});
					};

					if (historyDevices.length) {
						// 使用展开运算符创建新数组以避免直接修改原数组
						const devices = [...historyDevices];
						const deviceIndex = devices.findIndex(item =>
							item.MeasureID === currentDevice.MeasureID
							// item.BluetoothProtocol === currentDevice.BluetoothProtocol
						);

						if (deviceIndex === -1) {
							// 新设备，添加到数组
							const newDevice = prepareDevice({
								...currentDevice
							}, devices.length);
							devices.push(newDevice);
							updateStore(devices, devices.length - 1);
						} else {
							// 更新现有设备
							const updatedDevice = prepareDevice({
								...currentDevice
							}, deviceIndex);
							devices[deviceIndex] = updatedDevice;
							updateStore(devices, deviceIndex);
						}
					} else {
						// 首次存储
						const newDevice = prepareDevice({
							...currentDevice
						}, 0);
						updateStore([newDevice]);
					}

					// uni.setStorageSync('AgreementDevicesList')

					uni.$emit("GetDeviceName");

					//关闭当前页面，返回到前台界面
					uni.navigateBack({
						success: function() {
							uni.$emit("callBackDeviceType", that.selectedDevice);
						}
					})
				} else {
					uni.showToast({
						icon: 'none',
						title: "请先选择一个设备协议",

					})
				}
			}
		}
	}
</script>

<style lang="scss">
	* {
		padding: 0;
		margin: 0;
		box-sizing: border-box;
	}

	.page__content {
		/* 给顶部盒子安全高度 */
		// padding-top: var(--status-bar-height);
		// padding-left: 20px;
		// padding-right: 20px;
		// display: flex;
		// flex-direction: column;
		background-color: #f9f9f9;
		height: 100vh;

		&__main {
			padding: 0 20px;
		}

		.SiftBox {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 16rpx 0;

			.SiftBtn {
				width: fit-content;
				height: 28px;
				line-height: 20px;
				padding: 4px 8px;
				border-radius: 8px;
				background: #f6f6f6;
				font-size: 12px;
			}
		}

		.u-image {
			margin: 0 auto !important;
		}

		.CommonCard {
			position: relative;
			padding: 20px 0 10px;
			background-color: #f6f6f6;
			border-radius: 12px;
			box-shadow: 1px 1px 7px -6px #ced4d5;

			.CheckIcon {
				position: absolute;
				top: 3px;
				right: 3px;
				display: block;
				padding: 3px;
				background: green;
				border-radius: 50px;
			}

			.TextBox {
				text-align: center;
				margin-top: 20rpx;
				padding: 0 10px;

				.Text {
					font-size: 12px;
					display: block;
					word-wrap: break-word;
					word-break: break-all;
					overflow: hidden;
				}
			}
		}

		// 品牌筛选弹窗
		.page {
			width: 100%;
			height: 100%;
		}

		.wraper {
			display: flex;
			flex-direction: column;
			width: 100%;
			height: 100%;
		}

		.header {
			// background: rgb(8, 117, 94);
			color: #333;
			line-height: 60rpx;
			flex: 0 0 100rpx;
			/* 不放大不缩小固定100rpx */
			// background-color: pink;
		}

		.main {
			// height: 690rpx;
			position: relative;
		}

		.main-scroll {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
		}

		.main-list {
			// display: flex;
			// flex-wrap: wrap;
			// justify-content: space-between;
			margin-left: 2vw;
			margin-right: 2vw;

			// 品牌盒子
			.GridList {
				display: flex;
				flex-wrap: wrap;

				.GridCardBox {
					position: relative;
					box-shadow: 0 0 12px -9px #333;
					background-color: #fff;
					border-radius: 12px;
					overflow: hidden;
					width: 30%;
					margin: 5px;

					.textBox {
						text-align: center;
						padding: 4px 0;
						font-size: 14rpx;
					}
				}
			}
		}



		.footer {
			// line-height: 100rpx;
			flex: 0 0 100rpx;

		}


	}
</style>